package utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.sax.Excel03SaxReader;
import cn.hutool.poi.excel.sax.Excel07SaxReader;
import cn.hutool.poi.excel.sax.ExcelSaxReader;
import cn.hutool.poi.excel.sax.handler.RowHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Excel 处理上传工具类
 *
 * @Author 戚传文
 * @date 2018-04-04 8:32
 * ©2018赛鼎科技-版权所有
 */
public class ExcelUtils {


    /**
     * 生成导出的excel文件名称
     *
     * @author yaoliguo
     * @date 2019-08-08 18:47
     */
    public static String generationFileName() {

        return "ExcelExport_" + DateUtil.format(new Date(), "yyyyMMddHHmmss");
    }

    public static void importExcel(File file, RowHandler rowHandler) {

        importExcel(file, rowHandler, 1);
    }

    public static void importExcel(File file, RowHandler rowHandler, Integer sheet) {

        // 获取上传文件的路径
        String filePath = file.getName();
        InputStream in = null;
        //截取上传文件的后缀
        String fileSuffix = filePath.substring(filePath.lastIndexOf('.') + 1);

        ExcelSaxReader reader = createReader(fileSuffix, rowHandler);

        try {
            in = new FileInputStream(file);
            if (sheet != null) {
                reader.read(in, sheet);
            } else {
                reader.read(in, 0);
            }

        } catch (IOException e) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 根据后缀读取不同的版本的excel
     *
     * @author yaoliguo
     * @date 2018-04-08 15:45
     */
    private static ExcelSaxReader createReader(String fileSuffix, RowHandler rowHandler) {

        ExcelSaxReader reader = null;
        if ("xlsx".equals(fileSuffix)) {
            //Excel07SaxReader只支持Excel2007格式的Sax读取
            reader = new Excel07SaxReader(rowHandler);

        } else if ("xls".equals(fileSuffix)) {
            //Excel03SaxReader只支持Excel2003格式的Sax读取
            reader = new Excel03SaxReader(rowHandler);

        }

        return reader;
    }

    /*public static void exportExcel(HttpServletResponse resp, String fileName, List<Map<String, Object>> list) {

        exportExcel(resp, fileName, list, false);

    }

    public static void exportExcel(HttpServletRequest req, HttpServletResponse resp, String fileName, String title, List<Map<String, Object>> list) {

        exportExcel(req, resp, fileName, title, list, false);

    }

    public static void exportExcelWithCellStyle(HttpServletResponse resp, String fileName, List<Map<String, Object>> list) {

        exportExcel(resp, fileName, list, true);

    }

    public static void exportExcel(HttpServletResponse resp, String fileName, List<Map<String, Object>> list, boolean useMyExcelWriter) {
        String fileN = "";
        boolean isXlsx = false;
        try {

            if (StrUtil.isBlank(fileName)) {
                fileName = generationFileName();
            }
            fileN = new String(fileName.getBytes(), "iso-8859-1");

            if (fileName.endsWith(".xlsx")) {
                isXlsx = true;
            } else if (fileName.endsWith(".xls")) {
                isXlsx = false;
            } else {
                isXlsx = false;
                fileN += ".xls";
            }

        } catch (UnsupportedEncodingException e) {
            throw new ServiceException(ExcelExceptionEnum.CREATE_FILENAME_ERROR);
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/force-download");
        resp.setHeader("Content-Type", "application/vnd.ms-excel");
        resp.setHeader("Content-disposition", "attachment;filename=" + fileN);


        OutputStream out = null;
        try {
            out = resp.getOutputStream();
            //通过工具类创建writer，默认创建xls格式 true创建xlsx
            ExcelWriter writer = ExcelUtil.getWriter(isXlsx);
            if (useMyExcelWriter) {
                writer = getWriter(isXlsx);
            }
            //一次性写入数据
            writer.write(list);
            //写出到的目标流
            writer.flush(out);
            // 必须关闭writer，释放内存,不关闭不会释放
            out.flush();
            writer.close();
        } catch (IOException e) {
            throw new ServiceException(ExcelExceptionEnum.SERVER_ERROR);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    throw new ServiceException(ExcelExceptionEnum.COLSE_ERROR);
                }
            }
        }
    }

    public static void exportExcel(HttpServletRequest req, HttpServletResponse resp, String fileName, String title,
                                   List<Map<String, Object>> list, boolean useMyExcelWriter) {
        String fileN = "";
        boolean isXlsx = false;
        try {

            if (StrUtil.isBlank(fileName)) {
                fileName = "export";
            }

            String userAgent = req.getHeader("USER-AGENT");
            if (userAgent.contains("MSIE")) {
                fileN = new String(fileName.getBytes(), "UTF-8");
            } else if (userAgent.contains("Mozilla")) {
                fileN = new String(fileName.getBytes(), "ISO-8859-1");
            } else {
                fileN = new String(fileName.getBytes(), "UTF-8");
            }

            if (fileName.endsWith(".xlsx")) {
                isXlsx = true;
            } else if (fileName.endsWith(".xls")) {
                isXlsx = false;
            } else {
                isXlsx = false;
                fileN += ".xls";
            }

        } catch (UnsupportedEncodingException e) {
            throw new ServiceException(ExcelExceptionEnum.CREATE_FILENAME_ERROR);
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/force-download");
        resp.setHeader("Content-Type", "application/vnd.ms-excel");
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileN);

        OutputStream out = null;
        try {
            out = resp.getOutputStream();
            //通过工具类创建writer，默认创建xls格式 true创建xlsx
            ExcelWriter writer = ExcelUtil.getWriter(isXlsx);
            if (useMyExcelWriter) {
                writer = getWriter(isXlsx);
            }
            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(list.get(0).size() - 1, title);
            //一次性写入数据
            writer.write(list);
            //写出到的目标流
            writer.flush(out);
            // 必须关闭writer，释放内存,不关闭不会释放
            out.flush();
            writer.close();
        } catch (IOException e) {
            throw new ServiceException(ExcelExceptionEnum.SERVER_ERROR);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    throw new ServiceException(ExcelExceptionEnum.COLSE_ERROR);
                }
            }
        }
    }*/


}
